import webbrowser
from Tkinter import Tk, FALSE, BOTH
from ttk import Button, Frame
import watchdog


def show(gui_port, watchdog_port):
    window = Tk()
    MainDialog(window, gui_port, watchdog_port)
    window.protocol('WM_DELETE_WINDOW',
                    _close(window, watchdog_port))
    window.mainloop()


def _close(window, watchdog_port):
    def f():
        try:
            watchdog.send_command(watchdog_port, 'shutdown')
        except:
            print('APPDIALOG: Most probably watchdog is already shutdown.')
        finally:
            window.destroy()
    return f


class MainDialog(Frame):
    def __init__(self, parent, gui_port, watchdog_port):
        Frame.__init__(self, parent)
        self.parent = parent
        self.__init_ui()
        self.__gui_port = gui_port
        self.__watchdog_port = watchdog_port

    def __init_ui(self):
        self.__win_config()
        self.__grid_config()
        self.__win_content()
        self.pack(fill=BOTH, expand=1)

    def __win_content(self):
        start_browser_btn = Button(self,
                                   text=_("scopt.appdialog.begin_work"),
                                   command=self.__start_browser_btn_cmd)
        start_browser_btn.grid(row=1, column=1)

    def __start_browser_btn_cmd(self):
        webbrowser.open('http://localhost:{0}'.format(self.__gui_port))

    def __win_config(self):
        w = 500
        h = 350
        ws = self.parent.winfo_screenwidth()
        hs = self.parent.winfo_screenheight()
        x = (ws / 2) - (w / 2)
        y = (hs / 2) - (h / 2)
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
        self.parent.title("SCOPT")
        self.parent.resizable(width=FALSE, height=FALSE)

    def __grid_config(self):
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)

        self.rowconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)
